package com.favorite;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Solution802 {
    public List<Integer> eventualSafeNodes(int[][] graph) {
        int n = graph.length;
        int[] rudu = new int[n];
        List<List<Integer>> numList = new ArrayList<>();
        LinkedList<Integer> queue = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            numList.add(new ArrayList<>());
        }
        for (int i = 0; i < n; i++) {
            rudu[i] += graph[i].length;
            for (int j = 0; j < graph[i].length; j++) {
                numList.get(graph[i][j]).add(i);
            }
        }
        for (int i = 0; i < n; i++) {
            if (rudu[i] == 0) queue.add(i);
        }
        List<Integer> res = new ArrayList<>();
        while (!queue.isEmpty()) {
            int cur = queue.removeFirst();
            res.add(cur);
            List<Integer> list = numList.get(cur);
            for (int x : list) {
                rudu[x]--;
                if (rudu[x] == 0) queue.add(x);
            }
        }
        Collections.sort(res);
        return res;
    }
}
